package secondriver.springsubway.example.rpv.constraint;

import net.sf.oval.Validator;
import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
import net.sf.oval.context.OValContext;
import net.sf.oval.exception.OValException;

import java.io.Serializable;
import java.util.Map;

/**
 * Created by ZhangXiao on 2015/6/11.
 */
public class StartWithCheck extends AbstractAnnotationCheck<StartWith> {

    private String value;

    @Override
    public void configure(StartWith startWith) {
        super.configure(startWith);
        this.setValue(startWith.value());
    }

    @Override
    protected Map<String, ? extends Serializable> createMessageVariables() {
        Map messageVariables = Validator.getCollectionFactory().createMap();
        messageVariables.put("value", value);
        return messageVariables;
    }

    @Override
    public boolean isSatisfied(Object validatedObject, Object valueToValidate, OValContext context, Validator validator) throws OValException {
        if (null == valueToValidate) {
            return true;
        }
        if (valueToValidate instanceof String) {
            return ((String) valueToValidate).startsWith(value);
        }
        if (valueToValidate instanceof StringBuffer || valueToValidate instanceof StringBuffer || valueToValidate
                instanceof CharSequence) {
            valueToValidate.toString().startsWith(value);
        }
        try {
            return ((String) valueToValidate).startsWith(value);
        } catch (ClassCastException e) {
            return false;
        }
    }

    public void setValue(String value) {
        this.value = value;
        this.requireMessageVariablesRecreation();
    }
}